// import axios from "axios";
const axios = require('axios')

import store from '@/store/store'
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 请求拦截器
axios.interceptors.request.use(
  function(config) {
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)
// 响应拦截器
axios.interceptors.response.use(
  function(response) {
    return response
  },
  function(error) {
    return Promise.reject(error)
  }
)

// 封装axios的post请求
export function post(url, params) {
  return new Promise((resolve, reject) => {
    let headers = {}
    let user = store.getters.user
    if (user !== undefined) {
      headers = {
        headKey: JSON.stringify({ openId: user.openId })
      }
    }
    axios
      .post(url, params, {
        headers: headers
      })
      .then(response => {
        resolve(response.data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

// 封装axios的get请求
export function get(url, params) {
  return new Promise((resolve, reject) => {
    let headers = {}
    let user = store.getters.user
    if (user !== undefined && user.uid != 0) {
      if (params !== undefined) params.uid = user.uid
      headers = {
        headKey: JSON.stringify({ loginKey: user.loginKey, uid: user.uid })
      }
    }
    axios
      .get(url, {
        params: params,
        headers: headers
      })
      .then(response => {
        resolve(response.data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

export default {
  doPost(url, params) {
    return post(url, params)
  },
  doGet(url, params) {
    return get(url, params)
  }
}
